package com.hsh.controller;

import com.hsh.bean.Sleep;
import com.hsh.bean.User;
import com.hsh.service.SleepService;
import com.hsh.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Date;

@Controller
@RequestMapping("/sleep")
public class SleepController {

    @Resource
    private SleepService sleepService;

    @Resource
    private UserService userService;

    @RequestMapping("/list")
    public String list(Integer uid, Model model) {
        User user = userService.findById(uid);
        model.addAttribute("user", user);
        System.out.println("sleepController---list---user---"+user);
        return "/sleep/list";
    }

    @RequestMapping("/toAdd/{uid}")
    public String toAdd(@PathVariable Integer uid, Model model) {
        //TODO 获得用户名
        User user = userService.findById(uid);
        model.addAttribute("user", user);
        System.out.println("sleep---controller--toAdd---"+user);
        return "/sleep/add";
    }

    @RequestMapping("/add")
    public String add(Sleep sleep) {
        if (sleep.getSDate() == null) {
            sleep.setSDate(new Date());
        }
        sleepService.insert(sleep);
        return "redirect:/sleep/list?uid="+sleep.getUid();
    }

    @RequestMapping("/toUpdate/{sid}")
    public String toUpdate(@PathVariable Integer sid, Model model) {
        Sleep sleep = sleepService.findById(sid);
        model.addAttribute("sleep", sleep);
        return "/sleep/update";
    }

    @RequestMapping("/update")
    public String update(Sleep sleep) {
        sleepService.update(sleep);
        return "redirect:/sleep/list";
    }

}
